package mythread;

/**
 * @Auther: cty
 * @Date: 2020/1/8 13:17
 * @Description:  并发协作模型（线程通信模型）“生产者消费者模式”——>信号灯法
 * 借助标志位
 * @version: 1.0
 */
public class Ib_CooperationTest02 {
    public static void main(String[] args) {
        TV tv = new TV();
        Player player = new Player(tv);
        Watcher watcher = new Watcher(tv);
        player.start();
        watcher.start();
    }
}

//演员
class Player extends Thread{
    TV tv;
    public Player(TV tv){
        this.tv = tv;
    }

    @Override
    public void run() {
        for(int i=0; i<20; i++){
            if(i%2==0){
                this.tv.play(i+"-奇葩说");
            }else {
                this.tv.play(i+"-太污了，喝瓶立白洗洗嘴");
            }
        }
    }
}
//观众
class Watcher extends Thread{
    TV tv;
    public Watcher(TV tv){
        this.tv = tv;
    }

    @Override
    public void run() {
        for(int i=0; i<20; i++){
            tv.watch();
        }
    }
}
//电视
class TV{
    String voice;
    //信号灯
    //T 表示演员录制节目，观众等待
    //F 表示观众观看节目，演员休息
    boolean flag = true;

    //表演
    public synchronized void play(String voice){
        //演员休息
        if(!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了："+voice);
        this.voice = voice;
        flag = false;  //演员演好了，要休息了
        this.notifyAll();  //通知观众观看
    }

    //观看
    public synchronized void watch(){
        //观众等待
        if(flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观众听到了："+voice);
        flag = true;  //观众听完了，要等待了
        this.notifyAll();  //通知演员表演
    }
}
